require.config({baseUrl: '/js/lib',urlArgs: "v0.0.3"});
require(['zepto', 'lib'], function($, lib) {
  var fn = {}, lib = new lib();
  $.extend(fn, {
    orderType: (lib.getUrlParam('ot') ? lib.getUrlParam('ot') : '1'),
    pageNo: 1,
    pageSize: 20,
    noMore: false,
    orderTypeList: {'1': '待支付', '2': '待提货', '3': '已完成', '4': '已取消'},
    orderId: null,
    _this: null,
    init: function(){
      this.bindEvent();
      this.initPage();
      this.roll();
    },
    bindEvent: function(){
      var _t = this;
      /*删除/取消订单*/
      $(document).on("tap", ".ui-del-order, .ui-cancel-order", function(){
        lib.onLoading();
        var _this = this, url = 'order/deleteOrder.action', orderId = $(this).parents('.ui-per-shop').attr('data-orderId'), orderType = 1;
        if($(this).attr('class') === 'ui-cancel-order'){
          url = 'order/cancelOrder.action';
        }
        if($(_this).parents('.ui-per-shop').attr('data-orderSonId')){
          orderId = $(_this).parents('.ui-per-shop').attr('data-orderSonId')
          orderType = 2
        }
        lib.ajx(lib.getReq().ser + url, {orderId: orderId, orderType: orderType}, function(data){
          if(data.infocode === "0") $(_this).parents('.ui-per-shop').remove();
          else lib.showMessage(data.info);
        }, function(){
          lib.showMessage('网络延迟，请稍后再试');
        });
      });
      
      /*再次购买*/
      $(document).on("tap", ".ui-buy-again", function(){
        lib.onLoading();
        var _this = this, url = 'order/makeOrder.action', orderId = $(_this).parents('.ui-per-shop').attr('data-orderId'), orderType = 1;
        if($(_this).parents('.ui-per-shop').attr('data-orderSonId')){
          orderId = $(_this).parents('.ui-per-shop').attr('data-orderSonId')
          orderType = 2
        }
        location.href = `/order/confirm_order.html?oId=${orderId}&ot=${orderType}&mt=3`;
      });
      
      /*去支付*/
      $(document).on("tap", ".ui-go-pay", function(){
        lib.onLoading();
        if(window.browser.versions.weixin){
          if(lib.getIsOnline()){
              location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + lib.getReq().appid + 
              '&redirect_uri=http://api.chengshijiugui.com/csjgmanager/pay/wxPay.action&response_type=code&scope=snsapi_base&state='+ $(this).parents('.ui-per-shop').attr('data-orderId') + '#wechat_redirect';
              return;
          }else{
            location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + lib.getReq().appid + 
              '&redirect_uri=http://api.chengshijiugui.com/csjgmanager/pay/wxPay.action&response_type=code&scope=snsapi_base&state='+ $(this).parents('.ui-per-shop').attr('data-orderId')  + '#wechat_redirect';
          }
        }else{
          lib.ajx(lib.getReq().ser + '/pay/alipay.action', {orderId: $(this).parents('.ui-per-shop').attr('data-orderId'), originType: 1}, function(data){
            if(data.infocode === "0"){
              location.href = data.info;
            }else{
              lib.showMessage(data.info);
            }
          }, function(){
            lib.showMessage('网络错误,请稍后再试');
          });
        }
      });
      
      $(document).on("tap", ".ui-goods-info > li", function(){
        var orderId = $(this).parents('.ui-per-shop').attr('data-orderId');
        if($(this).parents('.ui-per-shop').attr('data-orderSonId')){
          orderId = $(this).parents('.ui-per-shop').attr('data-orderSonId')
        }
        location.href = `/order/order_detail.html?oId=${orderId}&ot=${_t.orderType}`
      })
      
      $(document).on("tap", ".ui-tuikuan", function(){
        $("#ui-tishi-k").remove();
        _t.orderId = $(this).parents('.ui-per-shop').attr('data-orderSonId')
        _t._this = this
        $('body').append(`
          <div id="ui-tishi-k" style="position: fixed;width:100%; height: 100%; top: 0;background-color: rgba(0,0,0,0.5)">
            <ul style="top: 50%;left: 50%;position: absolute;-webkit-transform: translate(-50%,-50%);transform: translate(-50%,-50%);width: 11.6rem;border-radius: 0.4rem;background-color: #ffffff;">
              <li style="padding-top: 0.8rem;text-align:center;font-size: 0.68rem; font-weight: 500; line-height: 1.56; letter-spacing: 2.7px; color: #333333;">申请退款</li>
              <li style="padding: 0 0.6rem;letter-spacing: 2.2px;">
                <p style="color: #999;font-size: 0.56rem;line-height: 3">退款时间:<span style="color: #333">${new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '  ' + new Date().getHours() + ':' + new Date().getMinutes()}</span></p>
                <p style="color: #999;font-size: 0.56rem;line-height: 3">退款金额:<span style="color: #333">${$(this).attr('data-orderSonPayline')}</span></p>
              </li>
              <li style="border-top: 1px solid #ddd;font-size: 0.68rem;text-align:center;line-height: 1.8rem;margin-top: 0.6rem">
                <div class="ui-tuikuan-cancel" style="width:50%;float:left;color: #666">取消</div>
                <div class="ui-tuikuan-confirm" style="overflow: hidden;color: #308eed;border-left: 1px solid #ddd;">确定</div>
              </li>
            </ul>
          </div>
        `);
      });
      
      $(document).on("tap", ".ui-tuikuan-cancel", function(){
        $("#ui-tishi-k").remove();
      });
      
      $(document).on("tap", ".ui-tuikuan-confirm", function(){
        lib.ajx(lib.getReq().ser + 'order/cancelOrder.action', {orderId: _t.orderId, orderType: 2}, function(data){
          if(data.infocode === "0") {
            lib.showMessage("退款提交成功  退款金额将在<br> 72小时内返还退款账户")
            $("#ui-tishi-k").remove();
            setTimeout(function(){
              $(_t._this).parents('.ui-per-shop').remove()
              if($(".ui-per-shop").length === 1){
                _t.pageNo = 1
                _t.initPage()
              }
            },1000)
          }
          else lib.showMessage(data.info);
        }, function(){
          lib.showMessage('网络延迟，请稍后再试');
        });
      });
    },
    initPage: function(){
      var _t = this;
      lib.ajx(lib.getReq().ser + '//order/orderList.action', {orderStatus: _t.orderType, pageNo: _t.pageNo, pageSize: _t.pageSize}, function(data){
        if(data.infocode === '0'){
          if(data.info.recordList.length < _t.pageSize) _t.noMore = true;
          if(_t.pageNo === 1 && data.info.recordList.length === 0) {
            lib.showMessage('暂无订单');
            return;
          }
          var h = '';
          $.each(data.info.recordList, function(key, val) {
            $.each(val.storage, function(K, V) {
              var shopGoodsNum = 0, shopTotalPrice = 0;
            	h +=  `<div class="ui-per-shop" data-orderId="${val.orderId}" data-orderSonId="${V.orderSonId}">
                      <div class="ui-shop-name">
                        <i>${V.storageName}</i>
                        <i class="ui-r-b" style="margin-top: 0.62rem;margin-left: 5px"></i>
                        <i style="${_t.orderType === '1' ?  'color: #333' : ''}">${_t.orderTypeList[_t.orderType]}</i>
                      </div>
                      <ul class="ui-goods-info">`
            	$.each(V.goodsList, function(k, v) {
            	  shopGoodsNum += Number(v.goodsNum);
            	  shopTotalPrice += Number(v.sellPrice) * Number(v.goodsNum);
                h +=  `<li >
                        <div class="ui-g-img"><img src="${lib.getReq().imgPath + v.mainPictureJpg}" /></div>
                        <ul class="ui-g-desc">
                          <li>${v.chName}</li>
                          <li>
                            <i class="ui-g-price">￥${v.sellPrice}<i> x${v.goodsNum}</i></i>
                            <i>实付款${(Number(v.sellPrice) * Number(v.goodsNum)).toFixed(2)}元</i>
                          </li>
                        </ul>
                      </li>`;
            		
            	});
              h +  `</ul>`;
               
              if(_t.orderType === "1") {
                if(V.goodsList.length > 1){
                  h += `<ul class="ui-order-operation ui-mar-t-20 ui-text-right">
                          <li>商品数目: ${shopGoodsNum}件</li>
                          <li>合计: ${shopTotalPrice.toFixed(2)}元</li>
                        </ul>`;
                }
                h += `<ul class="ui-order-operation ${V.goodsList.length > 1 ? '' : 'ui-mar-t-20'}">
                        <li class="ui-cancel-order">取消订单</li>
                        <li class="ui-go-pay">去支付</li>
                      </ul>
                    </div>`
               }else if(_t.orderType === "2"){
                 h += `<ul class="ui-order-operation ui-mar-t-20">
                        <li class="ui-tuikuan" data-orderSonPayline="${val.payOnline}">申请退款</li>
                        <li class="ui-buy-again">再次购买</li>
                      </ul>
                    </div>`
               }else if(_t.orderType === "3" || _t.orderType === "4"){
                 h += `<ul class="ui-order-operation ui-mar-t-20">
                        <li class="ui-del-order">删除订单</li>
                        <li class="ui-buy-again">再次购买</li>
                      </ul>
                    </div>`
               }
            });
          });
          
          $(".ui-all-goods").append(h);
        }else if(data.infocode === '2'){
          location.href = '/login.html?backUrl=' + lib.getBackUrl();
        }else{
          lib.showMessage(data.info);
        }
      }, function(){
        lib.showMessage('网络延迟，请稍后再试');
      });
    },
    roll: function(){
      var _t = this;
      $(window).scroll(function (){
          if(!noMore &&　$(window).scrollTop() >= $(document).height() - $(window).height()){
              _t.pageNo++ ;
              _t.initPage();
          }
      });
    }
  });
  fn.init();
});